package com.hippo4j.executor.support;

import com.gj.executor.support.ResizableCapacityLinkedBlockingQueue;
import com.hippo4j.executor.DynamicThreadPoolExecutor;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolBuilder {

    //线程池Id
    private String threadPoolId;

    private boolean isDynamic;

    private int corePoolSize;

    private int maximumPoolSize;

    private long keepAliveTime;

    private int queueCapacity;


    public static ThreadPoolBuilder builder() {
        return new ThreadPoolBuilder();
    }

    public ThreadPoolExecutor build() {
        if (isDynamic == true) {
            return new DynamicThreadPoolExecutor(
                    threadPoolId,
                    corePoolSize != 0 ? corePoolSize : 1,
                    maximumPoolSize != 0 ? maximumPoolSize : 3,
                    keepAliveTime != 0 ? keepAliveTime : 1,
                    TimeUnit.SECONDS,
                    new ResizableCapacityLinkedBlockingQueue<>(queueCapacity != 0 ? queueCapacity : 100),
                    r -> new Thread(r),
                    new ThreadPoolExecutor.AbortPolicy(),
                    false
            );
        } else {
            return new ThreadPoolExecutor(
                    corePoolSize,
                    maximumPoolSize,
                    keepAliveTime,
                    TimeUnit.SECONDS,
                    new LinkedBlockingDeque<>(queueCapacity),
                    r -> new Thread(r),
                    new ThreadPoolExecutor.AbortPolicy()
            );
        }
    }

    public ThreadPoolBuilder threadPoolId(String threadPoolId) {
        this.threadPoolId = threadPoolId;
        return this;
    }

    public ThreadPoolBuilder isDynamic(boolean flag) {
        this.isDynamic = false;
        return this;
    }

    public ThreadPoolBuilder queueCapacity(int queueCapacity) {
        this.queueCapacity = queueCapacity;
        return this;
    }

    public ThreadPoolBuilder corePoolSize(int corePoolSize) {
        this.corePoolSize = corePoolSize;
        return this;
    }

    public ThreadPoolBuilder maximumPoolSize(int maximumPoolSize) {
        this.maximumPoolSize = maximumPoolSize;
        return this;
    }

    public ThreadPoolBuilder keepAliveTime(long keepAliveTime) {
        this.keepAliveTime = keepAliveTime;
        return this;
    }
}
